package com.fish.anne.webapp.action;

import com.opensymphony.xwork2.Preparable;
import com.fish.anne.service.SystemSettingManager;
import com.fish.anne.model.SystemSetting;
import com.fish.anne.webapp.action.BaseAction;

import java.util.List;

public class SystemSettingAction extends BaseAction implements Preparable {
    private SystemSettingManager systemSettingManager;
    private List systemSettings;
    private SystemSetting systemSetting;
    private Long  settingId;

    public void setSystemSettingManager(SystemSettingManager systemSettingManager) {
        this.systemSettingManager = systemSettingManager;
    }

    public List getSystemSettings() {
        return systemSettings;
    }

    /**
     * Grab the entity from the database before populating with request parameters
     */
    public void prepare() {
        if (getRequest().getMethod().equalsIgnoreCase("post")) {
            // prevent failures on new
            String systemSettingId = getRequest().getParameter("systemSetting.settingId");
            if (systemSettingId != null && !systemSettingId.equals("")) {
                systemSetting = systemSettingManager.get(new Long(systemSettingId));
            }
        }
    }

    public String list() {
        systemSettings = systemSettingManager.getAll();
        return SUCCESS;
    }

    public void setSettingId(Long  settingId) {
        this. settingId =  settingId;
    }

    public SystemSetting getSystemSetting() {
        return systemSetting;
    }

    public void setSystemSetting(SystemSetting systemSetting) {
        this.systemSetting = systemSetting;
    }

    public String delete() {
        systemSettingManager.remove(systemSetting.getSettingId());
        saveMessage(getText("systemSetting.deleted"));

        return SUCCESS;
    }

    public String edit() {
        if (settingId != null) {
            systemSetting = systemSettingManager.get(settingId);
        } else {
            systemSetting = new SystemSetting();
        }

        return SUCCESS;
    }

    public String save() throws Exception {
        if (cancel != null) {
            return "cancel";
        }

        if (delete != null) {
            return delete();
        }

        boolean isNew = (systemSetting.getSettingId() == null);

        systemSettingManager.save(systemSetting);

        String key = (isNew) ? "systemSetting.added" : "systemSetting.updated";
        saveMessage(getText(key));

        if (!isNew) {
            return INPUT;
        } else {
            return SUCCESS;
        }
    }
}